'use strict';

let BaseController = require('./base.js');

class ManagerController extends BaseController {
	async index() {
		//查询管理员表并管理角色表
		let result = await this.ctx.model.Admin.aggregate([{
			$lookup: {
				from: 'role',
				localField: 'role_id',
				foreignField: '_id',
				as: 'role'
			}
			
		},{
			$project: {
				password: 0,
			},
		}])

		// let [password, add_time, status, ...data] = result;
		this.success(200, "请求成功", result)
	}

	async getRoleId() {
		const role_id = this.ctx.query.role_id;
		const result = await this.ctx.service.admin.getAuthList(role_id);
		this.success(200, "请求成功", result)
	}

	async getAllRole() {
		const result = await this.ctx.model.Role.find().sort({ sort: -1 });
		this.success(200, "请求成功", result)
	}

	async add() {
		let addResult = this.ctx.request.body;
		addResult.password = await this.service.tools.md5(addResult.password);
		//判断当前用户是否存在
		const adminResult = await this.ctx.model.Admin.findOne({
			"username": addResult.username
		});
		if (adminResult) {
			this.error(303, '此管理员已经存在');
		} else {
			const admin = new this.ctx.model.Admin(addResult);
			admin.save();
			this.success(200, '增加用户成功');
		}
	}

	async edit() {
		let {
			_id,
			password,
			mobile,
			email,
			role_id,
			is_super
		} = this.ctx.query;
		let result;
		if (password) {
			//修改密码
			password = await this.service.tools.md5(password);
			result = await this.ctx.model.Admin.updateOne({
				"_id": _id
			}, {
				password,
				mobile,
				email,
				role_id,
				is_super
			})
		} else {
			//不修改密码
			result = await this.ctx.model.Admin.updateOne({
				"_id": _id
			}, {
				mobile,
				email,
				role_id,
				is_super
			})
		}
		if (result.ok == 1) {
			this.success(200, '修改用户信息成功')
		} else {
			this.error(303, '修改用户信息失败')
		}
	}

	async delete() {
		let _id = this.ctx.query._id;
		const result = await this.ctx.model.Admin.deleteOne({
			"_id": _id
		});
		if (result.deletedCount != 0) {
			this.success(200, '删除用户信息成功')
		} else {
			this.error(303, '删除用户信息失败')
		}
	}

}

module.exports = ManagerController;
